<?php

namespace App\Modules\Apicrzs\Services\WeChat;

use App\Exceptions\Exception;
use EasyWeChat\Kernel\Exceptions\HttpException;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;
use EasyWeChat\MiniApp\Application;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Storage;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;

class Session
{

    /**
     * 静默登录，获取微信用户openid，后续与用户表绑定，并生成token。
     * @param $code
     * @return array|void
     * @throws Exception
     */
    public static function getToken($code)
    {
        if(!$code) {
            error('code错误');
        }
        $config = [
            'app_id' => config('services.wechat.mini_program.app_id'),
            'secret' => config('services.wechat.mini_program.secret'),
        ];

        try {
            $app = new Application($config);
            return $app->getUtils()->codeToSession($code);
        } catch (HttpException|InvalidArgumentException|TransportExceptionInterface
            |ClientExceptionInterface|DecodingExceptionInterface|RedirectionExceptionInterface
            |ServerExceptionInterface $e) {
            logger('出错了', [$e]);
            error($e->getMessage());
        }
    }

    /**
     * 获取用户手机号
     * @param $code
     * @return string
     * @throws RepastException
     */
    public static function getPhoneNumber($code): string
    {
        $config = [
            'app_id' => config('services.wechat.mini_program.app_id'),
            'secret' => config('services.wechat.mini_program.secret'),
        ];
        $app = new Application($config);
        try {
            $res = $app->phone_number->getUserPhoneNumber($code);
            return Arr::get($res,'phone_info.purePhoneNumber','');
        } catch (Exception|GuzzleException $e) {
            throw new RepastException($e->getMessage());
        }
    }
}
